package ca.mcgill.mni.bic;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class InputDialog extends Dialog {
	
	private Text response;
	private String responseString;
	
	public InputDialog (Shell parent, int style) {
		super (parent, style);
	}
	public InputDialog (Shell parent) {
		this (parent, 0); // your default style bits go here (not the Shell's style bits)
	}
	public InputDialog(Group group, int none) {
		// TODO Auto-generated constructor stub
		this (group.getShell(), none);
	}
	
	public String open(String message) {
		Shell parent = getParent();
		final Shell shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
		shell.setText("Input required");
		
		GridLayout gridLayout = new GridLayout();
	    gridLayout.numColumns = 1;
	    shell.setLayout(gridLayout);

		Label label = new Label(shell, SWT.NONE);
		label.setText(message);
		
		response = new Text(shell, SWT.SINGLE);
		response.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		response.addSelectionListener(new SelectionListener() {
		
			public void widgetSelected(SelectionEvent event) {
				
			}
		
			public void widgetDefaultSelected(SelectionEvent event) {
				// set the response text
				responseString = response.getText();
				
				// close the dialog...
				shell.close();
			}
		
		});
		
		// the buttons area
		Group buttons = new Group(shell, SWT.NONE);
		buttons.setLayout(new RowLayout(SWT.HORIZONTAL));
		
		Button cancel = new Button(buttons, SWT.PUSH);
		cancel.setText("Cancel");
		cancel.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				// clear the text
				responseString = null;
				
				// close the dialog...
				shell.close();
			}
		});
		
		Button ok = new Button(buttons, SWT.PUSH);
		ok.setText("OK");
		ok.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				// set the response text
				responseString = response.getText();
				
				// close the dialog...
				shell.close();
			}
		});

		buttons.layout();
		shell.layout();
		Point size = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT);
		shell.setSize(size.x, size.y);
		
		shell.open();
		Display display = parent.getDisplay();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) display.sleep();
		}

		return responseString;
	}
}
